import Vue from "vue";
// 导入路由
import VueRouter from "vue-router";
// 导入自定义的组件
import HomeView from "@/components/HomeView";
import LoginView from "@/components/LoginView";
import FeatureView from "@/components/FeatureView";
import AView from "@/components/AView";
import BView from "@/components/BView";
import CView from "@/components/CView";

// 注册路由
Vue.use(VueRouter)

// 定义路由
const routes = [
    {
        path: "/home", // 首页
        name: "HomeView",
        component: HomeView,
        children: [
            {
                path: "a",
                name: "AView",
                component: AView
            },
            {
                path: "b",
                name: "BView",
                component: BView
            },{
                path: "c",
                name: "CView",
                component: CView
            }
        ]
    },
    {
        path: "/login",
        name: "LoginView",
        component: LoginView,
        // 路由独享守卫
        beforeEnter: (to, from, next) => {
            console.log('路由独享守卫');
            next();
        }
    },
    {
        path: "/features",
        name: "FeatureView",
        component: FeatureView
    }
]

// 创建路由实例
const router = new VueRouter({
    // history模式
    mode: "history",
    base: process.env.BASE_URL,
    routes
})

// 利用全局守卫, 实现认证路由拦截
router.beforeEach((to, from, next) => {
    // 当前页面是不是登录页
    if (to.path == '/login') {
        console.log('登录页');
        next();
        return; // 当前函数中余下的代码全部略过
    }
    // 如果不是登录页, 判断是否已经登录
    const token = sessionStorage.getItem("token");
    console.log("令牌:", token);
    if (token != 'admin') {
        // 如果没有登录, 跳转到登录页面
        next('/login');
        return;
    }
    // 如果已经登录 放行
    next();
})

// 全局前置守卫
/*router.beforeEach((to, from, next) => {
    console.log(('beforeEach, 在路由切换前调用'));
    console.log('来源', from.path);
    console.log('目标', to.path);
    // 直接放行
    next();
})*/

// 全局解析守卫
/*router.beforeResolve((to, from, next) => {
    console.log(('beforeResolve, 异步路由组件解析完成之前调用'));
    console.log('来源', from.path);
    console.log('目标', to.path);
    next();
})*/

// 全局后置守卫
/*router.afterEach((to, from) => {
    console.log(('afterEach, 在路由切换之后调用'));
    console.log('来源', from.path);
    console.log('目标', to.path);
})*/

// 导出路由
export default router